package cn.edu.dlut.ssdut.foodCredit2012.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.edu.dlut.ssdut.foodCredit2012.model.Export;
import cn.edu.dlut.ssdut.foodCredit2012.model.News;
import cn.edu.dlut.ssdut.foodCredit2012.util.HibernateUtil;

public class NewsService {
	public void add(News news) {
		Session session = new HibernateUtil().getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		session.save(news);
		session.getTransaction().commit();
	}

	public void delete(News news) {
		Session session = new HibernateUtil().getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		session.delete(news);
		// session.delete(news.getFile());
		// session.delete(news.getImage());
		session.getTransaction();
	}

	public void update(News news) {
		Session session = new HibernateUtil().getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		session.update(news);
		session.update(news.getFile());
		session.update(news.getImage());
	}

	public News loadByNewsId(int id) {
		Session session = HibernateUtil.getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		News n = (News) session.get(News.class, id);
		session.getTransaction().commit();
		return n;
	}

	public List<News> loadNewsByCategory(int cid) {
		Session session = HibernateUtil.getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("from News where cid= :cid")
				.setInteger("cid", cid);
		List<News> list = (List<News>) query.list();
		session.getTransaction().commit();
		return list;
	}

	public List<News> loadNewPager(int cid, int start, int ps) {
		Session session = HibernateUtil.getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		Query query=session.createQuery("from News where cid= :cid").setInteger("cid", cid);
		int st=(start-1)*ps;
		query.setFirstResult(st);
		query.setMaxResults(ps);
		List<News> list=(List<News>)query.list();
		session.getTransaction().commit();
		return list;
	}

	public int getNewsCountByCategory(int cid) {
		Session session = HibernateUtil.getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		Long count = (Long) session.createQuery(
				"select count(*) from News where cid= :cid").setInteger("cid",
				cid).uniqueResult();
		session.getTransaction().commit();
		
		return Integer.parseInt(count.toString());
	}

	public List<News> newsList() {
		List<News> newsList = null;
		Session session = new HibernateUtil().getFileSessionFactory()
				.getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("from News");
		query.setFirstResult(2);
		query.setMaxResults(10);
		newsList = (List<News>) query.list();
		session.getTransaction().commit();
		return newsList;
	}

}
